var moment = require("moment");
var express = require('express');
var router = express.Router();

const log = require('../../../core/logger').getLogger("system");
const helper = require('../../util/helper');
const roleService = require('../../services/admin/roleService');

module.exports = router;

var __toParams = function(role){
    return {
        role_id: role.role_id,
        is: role.role_id + "_",
        role_name: role.role_name,
        description: role.description,
        created_at: role.created_at ? moment(role.created_at).format("YYYY-MM-DD HH:mm:ss") : "",
        modified_at: role.modified_at != "0000-00-00 00:00:00" ? moment(role.modified_at).format("YYYY-MM-DD HH:mm:ss") : ""
    }
};

/* GET users listing. */
router.get('/', (req, res, next) => {
    res.render('admin/role', {
        user: req.session.user,
        menus: req.session.menus,
        menu_active: req.session.menu_active['/roles'] || {},
        title: '角色管理',
        router: '/roles'
    });
});

router.get('/load', async(req, res, next) => {
    var {search, start, length, draw} = req.query;
    if (!start || !length || !draw) {
        return res.status(401).json("invoke error!");
    }

    var keywords = search?search.value.trim():null;
    var start  = parseInt(start) || 0;
    var length = parseInt(length) || 0;
    var draw   = parseInt(draw) || 0;

    roleService.getRoles(keywords, start, length, function (err, data) {
        if (!!err){
            return res.status(200).json({error:err.errCode, msg:err.message});
        }

        var rows = [];
        data.rows.forEach(function (role) {
            rows.push(__toParams(role));
        });

        var result = { draw: draw, recordsTotal: data.count, recordsFiltered: data.count, data: rows};
        return res.status(200).json(result);
    });
});

router.get('/save', async(req, res, next) => {
    var user = req.session.user;
    var role_id = req.query.e_id;
    var role_name = req.query.e_role_name;
    var description = req.query.e_description;
    if (!role_name || role_name.trim() == "") {
        return res.status(200).json({error:1, msg:"角色名不能为空!"});
    }

    if (role_id) {
        const roleInfo = {
            role_id: role_id,
            role_name: role_name.trim(),
            description: description.trim(),
            modified_id: user.id,
            modified_at: new Date()
        };
        roleService.updateRole(roleInfo, async function (err, result) {
            if (!!err) {
                return res.status(200).json({error:err.errCode, msg:err.message});
            }

            await helper.saveOpLog(user.id, user.user_name, user.name, "更新角色：" + role_name + ";ID: " + role_id);
            res.status(200).json({error: 0, msg: "角色更新成功"});
        });
    } else {
        const roleInfo = {
            role_name: role_name.trim(),
            description: description.trim(),
            creator_id: user.id,
            created_at: new Date(),
            modified_id: user.id,
            modified_at: new Date()
        };
        roleService.createRole(roleInfo, async function (err, result) {
            if (!!err) {
                return res.status(200).json({error:err.errCode, msg:err.message});
            }

            await helper.saveOpLog(user.id, user.user_name, user.name, "新增角色名称：" + role_name);
            res.status(200).json({error: 0, msg: "新增角色成功"});
        });
    }
});

router.delete('/delete', async(req, res, next) => {
    var ids = req.body.ids, user = req.session.user;
    if (!ids || ids.trim().length == 0) {
        res.status(200).json({error: 1, msg: '删除失败，必须选择一项'});
    }

    ids = ids.trim().split(",");
    roleService.destroyRoles(ids, async function (err, result) {
        if (!!err){
            return res.status(200).json({error: 1, msg: '删除失败，请联系管理员'});
        }

        await helper.saveOpLog(user.id, user.user_name, user.name, "删除角色ID: " + ids);
        return res.status(200).json({error: 0, msg: "角色删除成功"});
    });
});
